<template>
	<div>
		<el-form :inline="true"  style="padding-top: 10px;padding-left: 5px;">
			<el-form-item label="起止日期" prop="startandend" label-width="80px">
				<el-date-picker v-model="startandend" type="daterange" align="right" unlink-panels value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions2">
				</el-date-picker>
			</el-form-item>
			<!-- <el-form-item label="查询条件" prop="tempstring" label-width="80px">
				<el-input v-model="tempstring" style="width: 200px;" placeholder="请输入订单号"></el-input>
			</el-form-item> -->
			<el-form-item>
				<div style="float: left;">
					<el-button type="primary" @click="querybutton">查询</el-button>
				</div>
			</el-form-item>
			<el-form-item>
				<div style="float: left;margin-left: -10px;">
					<el-button type="primary" @click="addreturn_order">新增退货单</el-button>
				</div>
			</el-form-item>
		</el-form>
		<el-table :data="returnorderData" showOverflowTooltip style="width: 100%" :max-height="tabHeight" stripe border tooltip-effect="dark">
			<!--<el-table-column type="selection" width="50" > </el-table-column>-->
			<el-table-column prop="r_orderid" label="退单号" show-overflow-tooltip></el-table-column>
			<el-table-column prop="user_name" label="客户名称" show-overflow-tooltip></el-table-column>
			<el-table-column prop="r_order_price" label="金额" show-overflow-tooltip></el-table-column>
			<el-table-column prop="telephone" label="电话" show-overflow-tooltip></el-table-column>
			<el-table-column prop="create_time" label="退单时间" show-overflow-tooltip></el-table-column>
			<el-table-column prop="note" label="备注" show-overflow-tooltip></el-table-column>
			<el-table-column label="操作" width="160">
				<template slot-scope="scope">
					<el-button size="small" type="primary" @click="showServerEdit(scope.$index,scope.row)">详情</el-button>
					<el-button size="small" type="primary" @click="delServerEdit(scope.$index,scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		
		<el-dialog title="新增退单" :visible.sync="DialogVisible" :close-on-click-modal="false"  custom-class='el-dialog--large' width="80%">
			<el-form :inline="true" :model="addForm" :rules="addFormRules" ref='addForm'>
				<!-- <el-form-item label="客户" prop="user_name">
					<el-select v-model="addForm.user_id" disabled placeholder="请选择" style='width:100%'>
						<el-option v-for="item in userData" :key="item.user_id" :label='item.user_name' :value="item.user_id">
						</el-option>
					</el-select>
				</el-form-item> -->
				<el-form-item label="联系方式" prop="telephone">
					<el-input v-model="addForm.telephone"></el-input>
				</el-form-item>
				<el-form-item label="备注" prop="note">
					<el-input v-model="addForm.note"></el-input>
				</el-form-item>
				<el-form-item label="退单日期" prop="create_time">
					<el-date-picker v-model="addForm.create_time" type="date" value-format="yyyy-MM-dd" placeholder="选择退单日期" style='width:100%'></el-date-picker>
				</el-form-item>
				<div class='right'>
					<el-form-item>
						<el-button type="primary" @click="addNewTr">增加项目</el-button>
					</el-form-item>
				</div>
				<div style="dialogstyle">
					<el-table v-if="seenTable" :data="orderGoodsTable" border class='marginBottom'>
						<el-table-column label="商品" width="">
							<template slot-scope='scope'>
								<el-select v-model="scope.row.supplier" placeholder="请选择" @change="changgoods(scope.$index, scope.row)" filterable style='width:100%'>
									<el-option v-for="(item,index) in goodsData" :key="index" v-if="selectgoodsData.indexOf(item.gid)<0"  :label="item.goods_name+item.color_name+item.size_name" :value="item"></el-option>
								</el-select>
							</template>
						</el-table-column>
						
						<el-table-column label="商品编码" width="">
							<template slot-scope='scope'>
								<el-input size="small" disabled v-model="scope.row.goods_id"></el-input>
							</template>
						</el-table-column>
								
						<el-table-column label="商品名称" width="">
							<template slot-scope='scope'>
								<el-input size="small" disabled v-model="scope.row.goods_name"></el-input>
							</template>
						</el-table-column>
								
						<el-table-column label="尺码" width="">
							<template slot-scope="scope">
								<el-input disabled v-model="scope.row.size_id"></el-input>
							</template>
						</el-table-column>
								
						<el-table-column label="颜色" width="">
							<template slot-scope='scope'>
								<el-input disabled v-model="scope.row.color_id"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="数量" width="">
							<template slot-scope='scope'>
								<el-input v-model="scope.row.return_quantity" type="number" @change="changequantity(scope.$index, scope.row)"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="单价">
							<template slot-scope='scope'>
								<el-input disabled v-model="scope.row.price"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="小计">
							<template slot-scope='scope'>
								<el-input disabled v-model="scope.row.return_price"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<i class="el-icon-plus" title='添加一行' @click="addNewTr"></i>
								<i class="el-icon-delete" title='删除' @click="currentTrDel(scope.$index, scope.row)"></i>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div class='center'>
					<el-form-item>
						<el-button type="primary" @click="save_CheckIn(1,'addForm')">保存</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="reset_CheckIn">重置</el-button>
					</el-form-item>
				</div>
			</el-form>
		</el-dialog>
		
		<el-dialog title="退单详情" :visible.sync="dialogorder" >
			<el-form :inline="true" :model="orderForm" >
				<el-form-item label="客户" prop="user_name">
					<el-input v-model="orderForm.user_name"></el-input>
				</el-form-item>
				<el-form-item label="退单号" prop="r_orderid">
					<el-input v-model="orderForm.r_orderid"></el-input>
				</el-form-item>
				<el-form-item label="联系方式" prop="telephone">
					<el-input v-model="orderForm.telephone"></el-input>
				</el-form-item>
			</el-form>
			<el-table :data="returnsData" showOverflowTooltip stripe border tooltip-effect="dark" style="overflow: auto;max-height: 500px;">
				<el-table-column prop="goods_id" label="商品编码" show-overflow-tooltip></el-table-column>
				<el-table-column prop="goods_name" label="商品名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="size_name" label="尺码" show-overflow-tooltip></el-table-column>
				<el-table-column prop="color_name" label="颜色" show-overflow-tooltip></el-table-column>
				<el-table-column prop="return_quantity" label="数量" show-overflow-tooltip></el-table-column>
				<el-table-column prop="price" label="单价" show-overflow-tooltip></el-table-column>
				<el-table-column prop="return_price" label="小计" show-overflow-tooltip></el-table-column>
			</el-table>
		</el-dialog>
	</div>
</template>

<script>
	import axios from 'axios';
	import { selectallreturnorder,get_returnrecord,insert_returnorder,delete_returnorder,get_returnorderbyuser } from '../../api/order.js'
	import {selectalluser} from '../../api/user.js'
	import { fetchList,selectgoods,select_goodsstock } from '../../api/goods.js'
	export default {
		data() {
			return {
				returnorderData:[],
				userData:[],
				goodsData:[],
				tempstring:'',
				startandend:[],
				DialogVisible:false,
				addForm:{
					user_id:'',
					telephone:'',
					note:'',
					create_time:''
				},
				orderGoodsTable:[],
				pickerOptions2: {},
				addFormRules:{
					user_id: [
					    { required: true, message: '请输入客户', trigger: 'change' },
				    ],
				    consignee: [
					     { required: true, message: '请输入收货人', trigger: 'change' },
				    ],
				    telephone:[
				        { required: true, message: '请输入联系方式', trigger: 'change' },
				    ],
					shipping_address:[
					    { required: true, message: '请输入收货地址', trigger: 'change' },
					],
				    create_time:[
				    	 { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
				    ]
				},
				dialogorder:false,
				returnsData:[],
				orderForm:{
					'user_name':'',
					'r_orderid':'',
					'telephone':'',
					'consignee':'',
					'shipping_address':''
				},
				selectgoodsData:[],
				seenTable:true,
				tabHeight:500,
				queryform:{
					goods_type:'',
					state:1,
					sex:'',
					year:'',
					season:'',
					tempstring:''
				}
			};
		},
		methods:{
			querybutton(){
				this.returnorderData = [];
				if( this.startandend == []){
					if(this.startandend[0] == undefined){
						this.startandend[0] = '';
					}
					if(this.startandend[1] == undefined){
						this.startandend[1] = '';
					}
				}
				if(this.startandend == null ){
					this.startandend = [];
					this.startandend[0] = '';
					this.startandend[1] = '';
				}
				get_returnorderbyuser({parameter:this.tempstring,parameter1: this.startandend[0],parameter2: this.startandend[1]}).then(response => {
				   if(response.code == 0){
					   this.returnorderData = response.data;
				   }
				})
			},
			showExport(){
				
			},
			get_userList() {
				this.userData = [];
				selectalluser().then(response => {
					this.userData = response;
				})
			},
			get_goodsList() {
				this.goodsData = [];
			  select_goodsstock(this.queryform).then(response => {
				  if(response.code == 0){
					  this.goodsData = response.data;
						for(let i=0;i<this.goodsData.length;i++){
							this.goodsData[i].gid = i;
						}
					}
			  })
			},
			get_returnorder() {
				this.returnorderData = [];
			  selectallreturnorder().then(response => {
			     if(response.code == 0){
			    	this.returnorderData = response.data;
			    }
			  })
			},
			get_returnrecordbyid(val){
				this.returnsData = [];
				get_returnrecord({parameter:val}).then(response => {
					 if(response.code == 0){
						this.returnsData = response.data;
					}
			  })
			},
			addreturn_order:function(){
				var l = this.orderGoodsTable.length;
				this.orderGoodsTable.splice(0,l);
				this.DialogVisible = true;
				this.addForm.consignee = '';
				this.addForm.telephone = '';
				this.addForm.shipping_address='';
				this.addForm.create_time='';
				this.addForm.note = '';
				this.selectgoodsData = [];
				
				// 添加一条空白数据（设置id为1）即实现默认添加一行，
				this.orderGoodsTable.push({oid:1});
			},
			showServerEdit(index, row) {
				this.dialogorder = true;
				this.orderForm.user_name = row.user_name;
				this.orderForm.r_orderid = row.r_orderid;
				this.orderForm.telephone = row.telephone;
				this.orderForm.consignee = row.consignee;
				this.orderForm.shipping_address = row.shipping_address;
				this.get_returnrecordbyid(row.r_orderid);
				// this.selectRow=row;
			},
			delServerEdit(index, indexPath) {
				this.$confirm('是否确定删除'+indexPath.r_orderid+'退单?', '提示', {
					confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'
				}).then(() => {
					delete_returnorder({r_orderid:indexPath.r_orderid}).then(() => {
					  this.$notify({
						title: '成功',
						message: '删除成功',
						type: 'success'
					  })
					});
				}).catch(() => {
					this.$message({
						type: 'info',message: '已取消删除'
					});
				});
			},
			
			changgoods:function(index, row){
				// console.log(row,'row',index,row.supplier.id);
				let hindex = 0;
				for(let i=0;i<this.goodsData.length;i++){
					if(row.supplier.gid == this.goodsData[i].gid){
						hindex = i;
						break;
					}
				}
				this.orderGoodsTable[index]=this.goodsData[hindex];
				this.orderGoodsTable[index].return_quantity = 1;
				this.orderGoodsTable[index].return_price = this.orderGoodsTable[index].price *  Number(this.orderGoodsTable[index].return_quantity);
				
			},
			changequantity:function(index, row){
				this.orderGoodsTable[index].return_price = this.orderGoodsTable[index].price * Number(row.return_quantity);
				this.seenTable = false;
				this.$nextTick(function(){
					this.seenTable = true;
				})
			},
			save_CheckIn:function(type,formName){
				if(this.addForm.user_id == ''  || this.addForm.telephone == '' || this.addForm.create_time == ''){
					this.$notify({
					  title: '警告',
					  message: '请填写完整信息',
					  type: 'info',
					})
					return ;
				}
				console.log(this.orderGoodsTable[0].goods_id,'this.orderGoodsTable[0].goods_id')
				if(this.orderGoodsTable[0].goods_id == '' || this.orderGoodsTable[0].goods_id == undefined){
					this.$notify({
					  title: '警告',
					  message: '请选择商品',
					  type: 'info',
					})
					return ;
				}
				
				
				let num='';
				for(let i=0;i<7;i++){
					num+=Math.floor(Math.random()*10)
				}
				num = num.toString();
				let nowdate = '';
				let date = new Date();
				nowdate = (date.getFullYear()+ ((date.getMonth()+1)<10?'0'+(date.getMonth()+1):(date.getMonth()+1)) + ((date.getDate())<10?'0'+(date.getDate()):(date.getDate()))).toString();
				this.addForm.r_orderid ='R' + nowdate + num;
				this.addForm.r_order_price = 0;
				this.addForm.r_quantity = 0;
				
				for(let i=0;i<this.orderGoodsTable.length;i++){
					this.orderGoodsTable[i].r_orderid = this.addForm.r_orderid;
					this.addForm.r_order_price = this.addForm.r_order_price + this.orderGoodsTable[i].return_price;
					this.addForm.r_quantity = this.addForm.r_quantity + this.orderGoodsTable[i].return_quantity;
				}
				
				insert_returnorder(this.addForm).then(() => {
				  this.$notify({
				    title: '成功',
				    message: '创建成功',
				    type: 'success',
				    duration: 2000
				  })
				})
				
				
				axios({
				  method: 'post',
				  url: '/api/insert_returnrecord',
				  headers: {
					'Content-Type': 'application/json;charset=UTF-8'
				  },	 
					data:  this.orderGoodsTable
				}).then((res) => {
					 this.$notify({
					  title: '成功',
					  message: '创建成功',
					  type: 'success',
					  duration: 2000
					})
				})
				
				this.DialogVisible = false;
				this.querybutton();
				console.log(this.orderGoodsTable,'orderGoodsTable');

			},
			 addNewTr:function(){
				// 数据长度即为行数，也等同于最后一行的id，加一即为新增行id，
				var l = this.orderGoodsTable.length;
				// 数组内push一个空对象
				this.orderGoodsTable.push({oid:l+1});
				for(let i=0;i<this.goodsData.length;i++){
					for(let j=0;j<this.orderGoodsTable.length;j++){
						if( this.orderGoodsTable[j].gid == this.goodsData[i].gid){
							if(this.selectgoodsData.indexOf(this.orderGoodsTable[j].gid)<0){
								this.selectgoodsData.push(this.orderGoodsTable[j].gid);
							}
						}
					}
				}
			},
			 reset_CheckIn:function(){ 
				var l = this.orderGoodsTable.length;
				this.orderGoodsTable.splice(0,l);
				this.orderGoodsTable.push({id:1});
			},
			cloneAddThisTr:function(index, row){
				var rowStr = JSON.stringify(row);
				var row = JSON.parse(rowStr);
				var l = this.orderGoodsTable.length;
				// 对复制的row的id加一，
				row.id = l+1;
				// var row = JSON.parse(JSON.stringify(row));
				// 复制上一行数据添加到新行，但导致两行数据双向绑定、同步被修改
				// 因为当前行的 row 数据并不是一个纯粹的JSON对象，经转换为JSON字符串再转换回JSON对象，成为纯粹的JSON对象，添加到数据数组对象里，则不会和当前 row 产生数据双向绑定，
				this.orderGoodsTable.push(row);
			},
			
			// 删除当前行
			currentTrDel: function(index, row) {
				console.log('index：' + index);
				// console.log(row);
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					// id 为准备删除的数据的id，这些数据只存在于当前页面，所以只需要这些数据的id不重复即可，
					  let para = { id: row.id };
					this.orderGoodsTable.splice(index,1);
					for(let i=0;i<this.selectgoodsData.length;i++){
						if(row.gid ==this.selectgoodsData[i]){
							this.selectgoodsData.splice(i,1);
						}
					}
				}).catch(() => {
			
				});
			},

		},
		created(){
			this.tabHeight = document.documentElement.scrollHeight - 160 || document.body.scrollHeight -160;
			var storageuser = JSON.parse(localStorage.getItem("userInfo"));
			this.tempstring = storageuser.user_id;
			this.addForm.user_id = storageuser.user_id;
			this.querybutton();
			this.get_userList();
			this.get_goodsList();
		}
	}
</script>

<style>

</style>
